define([
  'underscore',
  'views/View',
  'hbs!template/users/users-selection'
], function(_, View, template){
  var UsersSelection = View.extend({
    template: template,

    events: {
      "click a[name=add]":              "addDst",
      "click a[name=delete]":           "removeDst"
    },
    
    initialize: function(options) {
      options || (options = {});
      View.prototype.initialize.call(this, options);

      this.collection.bind("reset", this.render, this);
      this.type = options.type;

      // Create array to store the selected receivers
      this.receivers = [];
    },
    
    addDst: function(evt) {
      var id = this._getDataId(evt),
          dst = this.collection.get(id);
      if(this.receivers.indexOf(dst) === -1) {
        this.receivers.push(dst);
        this.render();
      }

      this.trigger("update:selection");
    },

    removeDst: function(evt) {
      var id = this._getDataId(evt),
          dst = this.collection.get(id),
          index = this.receivers.indexOf(dst);
      if(index !== -1) {
        this.receivers.splice(index, 1); // Remove the selected receiver.
        this.render();
      }
      this.trigger("update:selection");
    },

    _getDataId: function(evt) {
      evt.preventDefault();
      var dataid =  this.$(evt.currentTarget).data("id");
      return dataid;
    },

    getReceivers: function() {
      return this.receivers;
    },

    
    getRenderData: function() {
      var data = {}, // The returned json object
          internals = [],
          that = this;

      //console.log(this.collection);
      data.pagination = this.collection.pagination.info();
      _.each(data.pagination.models, (function(internal){
        var intern = {};
        if(that.receivers.indexOf(internal) != -1) {
          intern.data = internal.toJSON();
          intern.selected = true;
        } else {
          intern.data = internal.toJSON();
          intern.selected = false;
        }
        internals.push(intern);
      }));
      data.internals = internals;
      if(this.type === 'familiar') {
        data._familiar = true;
      } else if(this.type === 'internal') {
        data._internal = true;
      } else if(this.type === 'admin') {
        data._admin = true;
      }
      console.log(data);
      return data;
    }
  });
  
  return UsersSelection;
});